#include <stdio.h>
#include <stdlib.h>
// ssize_t read(int fd, void *buf, size_t count)
// int write(int fd, void *buf, size_t count)
#include <unistd.h>
// open function in 'fcntl.h'
// int open(const char *pathname, int flags[, mode_t mode])
// flags: O_WRONLY | O_RDONLY | O_CREAT | O_RDWR | OTRUNC | O_APPEND
// mode: S_IRWXU : 00700权限, 代表该文件所有者具有可读、可写及可执行的权限
#include <fcntl.h>

#define BUFFSIZE 8192

void err_sys(const char * info) {
	fprintf(stderr, "%s\n",info);
}

int usage(const char * argv[]) {
	fprintf(stderr, "Usage:\n\t %s file1 file2.\n", argv[0]);
	return 0;
}

int main(int argc, const char * argv[]) {
	int n;
	char buf[BUFFSIZE];

	if(argc != 3) {
		if(argc < 3)
			err_sys("Too few arguments.");
		else
			err_sys("Too many arguments.");
		usage(argv);
		exit(EXIT_FAILURE);
	}

	int in, out;
	if((in = open(argv[1], O_RDONLY)) == -1) {
		err_sys("Open Error.");
		exit(EXIT_FAILURE);
	}

	// fopen(argv[2], "w");

	if((out = open(argv[2], O_WRONLY | O_CREAT, S_IRWXU)) == -1) {
		err_sys("Open Error.");
		exit(EXIT_FAILURE);
	}
	
	while((n = read(in, buf, BUFFSIZE)) > 0)
		if(write(out, buf, n) != n) {
			err_sys("Write error.");
			exit(EXIT_FAILURE);
		}
	
	if(n < 0) {
		err_sys("Read error.");
		exit(EXIT_FAILURE);
	}

	return 0;
}
